package com.glory.eapequipmentmonitor.activity;

import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IFillFormatter;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.Utils;
import com.glory.eapequipmentmonitor.R;
import com.glory.eapequipmentmonitor.bean.BaseResponseBean;
import com.glory.eapequipmentmonitor.bean.OpLotBean;
import com.glory.eapequipmentmonitor.bean.ResponseQueryBean;
import com.glory.eapequipmentmonitor.utils.NetUtils;
import com.glory.eapequipmentmonitor.view.MyMarkerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.base.FreeUI_BaseActivity;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class SearchLotActivity extends FreeUI_BaseActivity {


    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.lineChart)
    LineChart chart;
    @BindView(R.id.etLotId)
    EditText etLotId;
    @BindView(R.id.etEmpId)
    EditText etEmpId;
    @BindView(R.id.tvLotTitle)
    TextView tvLotTitle;
    @BindView(R.id.tvSearch)
    TextView tvSearch;
    @BindView(R.id.tvLotType)
    TextView tvLotType;
    @BindView(R.id.tvLotNum)
    TextView tvLotNum;
    @BindView(R.id.tvProName)
    TextView tvProName;
    @BindView(R.id.tvStep)
    TextView tvStep;
    @BindView(R.id.tvStepDesc)
    TextView tvStepDesc;
    @BindView(R.id.tvRecipe)
    TextView tvRecipe;
    @BindView(R.id.tvLotState)
    TextView tvLotState;
    @BindView(R.id.tvHoldState)
    TextView tvHoldState;
    @BindView(R.id.tvScrap)
    TextView tvScrap;
    @BindView(R.id.tvUser)
    TextView tvUser;
    @BindView(R.id.tvProcessName)
    TextView tvProcessName;
    @BindView(R.id.tvProcessVersion)
    TextView tvProcessVersion;
    @BindView(R.id.tvLiuchengName)
    TextView tvLiuchengName;
    @BindView(R.id.tvLiuchengVersion)
    TextView tvLiuchengVersion;
    @BindView(R.id.tvWoId)
    TextView tvWoId;
    @BindView(R.id.tvGrade)
    TextView tvGrade;
    @BindView(R.id.tvPriority)
    TextView tvPriority;

    @BindView(R.id.flMain)
    FrameLayout flMain;
    @BindView(R.id.tvBtnOne)
    TextView tvBtnOne;
    @BindView(R.id.tvBtnTwo)
    TextView tvBtnTwo;
    @BindView(R.id.tvBtnThree)
    TextView tvBtnThree;

    private LimitLine ll1, ll2;
    private LineDataSet set1;

    private ResponseQueryBean.LOTBean lotBean;
    private boolean isLot = false;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_search_lot;
    }

    @Override
    protected void initView() {
        tvBtnOne.setText("进站");
        tvBtnTwo.setText("出站");
        tvBtnThree.setText("退站");
    }

    @Override
    protected void initData() {
        {   // // Chart Style // //

            // background color
            chart.setBackgroundColor(Color.WHITE);

            // disable description text
            chart.getDescription().setEnabled(false);

            // enable touch gestures
            chart.setTouchEnabled(true);

            // set listeners
//            chart.setOnChartValueSelectedListener(this);
            chart.setDrawGridBackground(false);

            // create marker to display box when values are selected
            MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view);

            // Set the marker to the chart
            mv.setChartView(chart);
            chart.setMarker(mv);

            // enable scaling and dragging
            chart.setDragEnabled(true);
            chart.setScaleEnabled(true);
            // chart.setScaleXEnabled(true);
            // chart.setScaleYEnabled(true);

            // force pinch zoom along both axis
            chart.setPinchZoom(true);
        }

        XAxis xAxis;
        {   // // X-Axis Style // //
            xAxis = chart.getXAxis();

            // vertical grid lines
            xAxis.enableGridDashedLine(10f, 10f, 0f);
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        }

        YAxis yAxis;
        {   // // Y-Axis Style // //
            yAxis = chart.getAxisLeft();

            // disable dual axis (only use LEFT axis)
            chart.getAxisRight().setEnabled(false);
            // horizontal grid lines
            yAxis.enableGridDashedLine(10f, 10f, 0f);

            // axis range
            yAxis.setAxisMaximum(200f);
            yAxis.setAxisMinimum(0f);
        }


        {   // // Create Limit Lines // //
            LimitLine llXAxis = new LimitLine(9f, "Index 10");
            llXAxis.setLineWidth(4f);
            llXAxis.enableDashedLine(10f, 10f, 0f);
            llXAxis.setLabelPosition(LimitLine.LimitLabelPosition.LEFT_TOP);
            llXAxis.setTextSize(10f);
            llXAxis.setLineColor(R.color.free_ui_glory_theme_color);

            ll1 = new LimitLine(160f, "上限");
            ll1.setLineWidth(4f);
            ll1.enableDashedLine(10f, 10f, 0f);
            ll1.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);
            ll1.setTextSize(10f);
            ll1.setLineColor(R.color.free_ui_glory_theme_color);

            ll2 = new LimitLine(40f, "下限");
            ll2.setLineWidth(4f);
            ll2.enableDashedLine(10f, 10f, 0f);
            ll2.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_BOTTOM);
            ll2.setTextSize(10f);
            ll2.setLineColor(R.color.free_ui_glory_theme_color);

            // draw limit lines behind data instead of on top
            yAxis.setDrawLimitLinesBehindData(true);
            xAxis.setDrawLimitLinesBehindData(true);

            // add limit lines
            yAxis.addLimitLine(ll1);
            yAxis.addLimitLine(ll2);
//            xAxis.addLimitLine(llXAxis);
        }

        // draw points over time
        chart.animateX(1000);

        // get the legend (only possible after setting data)
        Legend l = chart.getLegend();

        // draw legend entries as lines
        l.setForm(Legend.LegendForm.LINE);
        setData(24, 180);
    }

    private void setData(int count, float range) {

        ArrayList<Entry> values = new ArrayList<>();

        for (int i = 0; i < count; i++) {
            float val = (float) (Math.random() * range) - 30;
            values.add(new Entry(i, val));
        }


        if (chart.getData() != null &&
                chart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) chart.getData().getDataSetByIndex(0);
            set1.setValues(values);
            set1.notifyDataSetChanged();
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();
        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(values, "时间(小时)");
            set1.setDrawIcons(false);

            // draw dashed line
            set1.enableDashedLine(10f, 5f, 0f);

            // black lines and points
            set1.setColor(R.color.free_ui_glory_theme_color);
            set1.setCircleColor(R.color.free_ui_glory_theme_color);

            // line thickness and point size
            set1.setLineWidth(1f);
            set1.setCircleRadius(3f);

            // draw points as solid circles
            set1.setDrawCircleHole(false);

            // customize legend entry
            set1.setFormLineWidth(1f);
            set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
            set1.setFormSize(15.f);

            // text size of values
            set1.setValueTextSize(9f);
            set1.setValueTextColor(R.color.free_ui_glory_theme_color);

            // draw selection line as dashed
            set1.enableDashedHighlightLine(10f, 5f, 0f);

            // set the filled area
            set1.setDrawFilled(true);
            set1.setFillFormatter(new IFillFormatter() {
                @Override
                public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
                    return chart.getAxisLeft().getAxisMinimum();
                }
            });

            // set color of filled area
            if (Utils.getSDKInt() >= 18) {
                // drawables only supported on api level 18 and above
                Drawable drawable = ContextCompat.getDrawable(this, R.drawable.fade_theme);
                set1.setFillDrawable(drawable);
            } else {
                set1.setFillColor(Color.BLACK);
            }
            ArrayList<ILineDataSet> dataSets = new ArrayList<>();
            dataSets.add(set1); // add the data sets

            // create a data object with the data sets
            LineData data = new LineData(dataSets);

            // set data
            chart.setData(data);
        }
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("批次信息查询");
//        freeUI_titleView.setRightListener(R.drawable.refresh, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });
        return new FreeUI_AddViewEntity("header", llMain);
    }

    @OnClick({R.id.tvSearch, R.id.tvBtnOne, R.id.tvBtnTwo, R.id.tvBtnThree, R.id.rbLot, R.id.rbDurable})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvSearch:
                if (etEmpId.getText().toString().isEmpty()) {
                    showToast("请输入设备号", false);
                    return;
                }
                if (etLotId.getText().toString().isEmpty()) {
                    showToast("请输入载具/批次号", false);
                    return;
                }
                searchData(etLotId.getText().toString(), etEmpId.getText().toString());
                break;
            case R.id.tvBtnOne:
                if (lotBean == null) {
                    showToast("还没请求到lot信息", false);
                    return;
                }
                requestOp("MES.LOTTRACKIN");
                break;
            case R.id.tvBtnTwo:
                if (lotBean == null) {
                    showToast("还没请求到lot信息", false);
                    return;
                }
                requestOp("MES.LOTTRACKOUT");
                break;
            case R.id.tvBtnThree:
                if (lotBean == null) {
                    showToast("还没请求到lot信息", false);
                    return;
                }
                requestOp("MES.LOTABORT");
                break;
            case R.id.rbLot:
                isLot = true;
                tvLotTitle.setText("批次号：");
                etLotId.setHint("请输入批次号");
                break;
            case R.id.rbDurable:
                isLot = false;
                tvLotTitle.setText("载具号：");
                etLotId.setHint("请输入载具号");
                break;
        }
    }

    private void searchData(String lotId, String empId) {
        JSONObject jsonObject = new JSONObject();
        try {
            if (isLot) {
                jsonObject.put("LOTID", lotId);
                jsonObject.put("ACTIONTYPE", "LOTINFOBYID");
            } else {
                jsonObject.put("DURABLE", lotId);
                jsonObject.put("ACTIONTYPE", "LOTINFOBYDURABLE");
            }
            jsonObject.put("EQUIPMENTID", empId);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestQueryLot(jsonObject, new FreeUI_DialogEntityCallBack<BaseResponseBean<ResponseQueryBean>>(
                new TypeToken<BaseResponseBean<ResponseQueryBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseResponseBean<ResponseQueryBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true)) {
                    flMain.setVisibility(View.VISIBLE);
                    lotBean = response.body().getResponse().getBody().getLOT();
                    setUpData();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<ResponseQueryBean>> response) {
                super.onError(response);
                loadError(response.getException(), "lotQuery");
            }
        });
    }

    private void requestOp(final String method) {
        JSONObject jsonObject = new JSONObject();
        try {
            List<OpLotBean> lotList = new ArrayList<>();
            OpLotBean opLotBean = new OpLotBean();
            opLotBean.setLOTID(lotBean.getLOTID());
            lotList.add(opLotBean);
            jsonObject.put("LOTLIST", new JSONArray(new Gson().toJson(lotList)));
            jsonObject.put("EQUIPMENTID", etEmpId.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestNoResponse(jsonObject, method, new FreeUI_DialogEntityCallBack<BaseResponseBean<?>>(
                new TypeToken<BaseResponseBean<?>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseResponseBean<?>> response) {
                if (response.body().isSuccess(getApplicationContext(), false)) {
                    switch (method) {
                        case "MES.LOTTRACKIN":
                            showToast("进站成功", true);
                            break;
                        case "MES.LOTTRACKOUT":
                            showToast("出站成功", true);
                            break;
                        case "MES.LOTABORT":
                            showToast("退站成功", true);
                            break;
                    }
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            SearchLotActivity.this.finish();
                        }
                    }, 2000);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<?>> response) {
                super.onError(response);
                loadError(response.getException(), method);
            }
        });
    }

    private void setUpData() {
        tvLotType.setText(lotBean.getLOTTYPE());
        tvLotNum.setText(lotBean.getMAINQTY());
        tvProName.setText(lotBean.getPARTNAME());
        tvStep.setText(lotBean.getSTEPNAME());
        tvStepDesc.setText(lotBean.getSTEPDESC());
        tvRecipe.setText(lotBean.getRECIPENAME());
        tvLotState.setText(lotBean.getSTATE());
        tvHoldState.setText(lotBean.getHOLDSTATE());

        tvProcessName.setText(lotBean.getPROCESSNAME());
        tvProcessVersion.setText(lotBean.getPROCESSVERSION());
        tvLiuchengName.setText(lotBean.getPROCEDURENAME());
        tvLiuchengVersion.setText(lotBean.getPROCEDUREVERSION());
        tvWoId.setText(lotBean.getWOID());
        tvGrade.setText(lotBean.getGRADE1());
        tvPriority.setText(lotBean.getPRIORITY());
    }
}
